'use strict';

/**
 * Created by twer on 15/3/1.
 */
angular.module('microblog').controller('MicroBlogListCtrl', [
    '$scope',
    '$routeParams',
    '$rootScope',
    'MicroBlogListService',
    'PageConstant',
    'PathSuffixConstant',
    'CommentQueryService',
    'CommentModifyService',
    'MicroBlogEditService',
    'ProfilePhotoService',
    'PhotoHost',
    function ($scope, $routeParams, $rootScope, MicroBlogListService, PageConstant, PathSuffixConstant, CommentQueryService, CommentModifyService, MicroBlogEditService, ProfilePhotoService, PhotoHost) {
        $rootScope.visitedUserId = $routeParams.userId;
        var author = {identity: $routeParams.userId};

        $scope.$on('MicroBlogCreatedEvent', function (event, data) {
            var createdMicroBlog = {
                _id: data._id,
                content: data.content,
                createTime: new Date(),
                author: {
                    identity: author.identity,
                    name: $scope.visitedUserName
                }
            };
            ProfilePhotoService.query({userId: createdMicroBlog.author.identity}, function (response) {
                createdMicroBlog.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
            });
            $scope.microblogs.push(createdMicroBlog);
        });

        /**
         * 微博查询
         *
         * @param pageNumber
         */
        $scope.query = function (pageNumber) {
            $scope.microblogs = [];

            var queryCondition = {
                offset: (pageNumber - 1) * PageConstant.countPerPage,
                countPerPage: PageConstant.countPerPage
            };

            queryCondition.author = author.identity + PathSuffixConstant;
            MicroBlogListService.query(queryCondition, function (response) {
                results(response);
            });
        };

        /**
         * 微博删除
         *
         * @param microblog
         */
        $scope.remove = function (microblog) {
            if (confirm('是否删除该微博？')) {
                MicroBlogEditService.remove({id: microblog._id}, function () {
                    var microblogs = [];
                    angular.forEach($scope.microblogs, function (v) {
                        if (v._id != microblog._id) {
                            microblogs.push(v);
                        }
                    });
                    $scope.microblogs = microblogs;
                });
            }
        };

        /**
         * 增加评论
         *
         * @param microblog
         */
        $scope.addComment = function (microblog) {
            if (microblog.newReply == '') {
                alert('请录入评论内容！');
                return;
            }

            var newComment = {
                referenceId: microblog._id,
                author: {
                    identity: $rootScope.currentUser.id,
                    name: $rootScope.currentUser.name
                },
                commentType: 'micro_blog',
                content: microblog.newReply
            };

            CommentModifyService.add(newComment, function (response) {
                microblog.comments = microblog.comments || [];
                var createdComment = {
                    _id: response._id,
                    content: newComment.content,
                    author: newComment.author,
                    createTime: {
                        $date: new Date()
                    }
                };
                ProfilePhotoService.query({userId: createdComment.author.identity}, function (response) {
                    createdComment.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
                });
                microblog.comments.push(createdComment);
                microblog.replies += 1;
                $scope.closeReply(microblog);
                microblog.newReply = '';
            });
        };

        /**
         * 需要回复
         *
         * @param host
         */
        $scope.openReply = function (host) {
            host.needReply = true;
        };

        /**
         * 关闭回复
         *
         * @param comment
         */
        $scope.closeReply = function (host) {
            host.needReply = false;
            host.newReply = '';
        };

        /**
         * 对评论增加一个回复
         *
         * @param comment
         */
        $scope.addReply = function (comment) {
            if (!comment.newReply || comment.newReply == '') {
                alert('请录入回复内容！');
                return;
            }

            var newReply = {
                referenceId: comment._id,
                author: {
                    identity: $rootScope.currentUser.id,
                    name: $rootScope.currentUser.name
                },
                commentType: 'micro_blog',
                content: comment.newReply,
                object: comment.author
            };

            CommentModifyService.add(newReply, function (response) {
                comment.comments = comment.comments || [];
                var createdReply = {
                    _id: response._id,
                    content: newReply.content,
                    author: newReply.author,
                    createTime: {
                        $date: new Date()
                    },
                    object: newReply.object
                };
                ProfilePhotoService.query({userId: createdReply.author.identity}, function (response) {
                    createdReply.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
                });
                comment.comments.push(createdReply);
                $scope.closeReply(comment);
                comment.newReply = '';
            });
        };


        function results(response) {
            $scope.microblogs = response.results;
            $scope.totalCount = response.totalCount;

            setPhotosUri($scope.microblogs);

            angular.forEach($scope.microblogs, function (v) {
                v.replies = v.replies ? v.replies : 0;
                CommentQueryService.query({
                    hostId: v._id + PathSuffixConstant,
                    type: 'micro_blog'
                }, function (response) {
                    v.comments = response.results;
                    setPhotosUri(v.comments);
                });
            });
        }

        function setPhotosUri(objectList) {
            angular.forEach(objectList, function (object) {
                ProfilePhotoService.query({userId: object.author.identity}, function (response) {
                    object.author.photoUri = PhotoHost + 'cdrmimg/' + response.photoId + '?w=50&h=50';
                });
                if (object.comments) {
                    setPhotosUri(object.comments);
                }
            });
        }

        $scope.query(1);

    }]);
